import Config from '@/config'

export const arrToObj = (arr) => {
	return arr.reduce((prev, current) => {
		if (current.name) {
			prev[current.name] = current;
		}
		return prev;
	}, {})
}

export const objToArr = (obj) => {
	return Object.keys(obj).map(key => obj[key])
}

export function throttle(fn, gapTime = 1500) {
	let _lastTime = null

	// 返回新的函数
	return (function() {
		let _nowTime = +new Date()

		if (_nowTime - _lastTime > gapTime || !_lastTime) {
			fn.apply(this, arguments) //将this和参数传给原函数
			_lastTime = _nowTime
		}
	})()
}

//定义检测数据类型的功能函数
export function checkedType(target) {
	return Object.prototype.toString.call(target).slice(8, -1);
}

export function calcDateTimeDiff(d1, d2) {
	let dateBegin = new Date(d1.replace(/-/g, "/")); //将-转化为/，使用new Date
	let dateEnd = new Date(d2.replace(/-/g, "/"))

	let dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数

	let dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
	let month = Math.floor(dayDiff / 30)
	let quarter = Math.floor(dayDiff / 30 / 3)
	let year = Math.floor(dayDiff / 365)

	console.log('calcDateTimeDiff: ', dayDiff, month, quarter, year)

	if (year > 0) return `${year}年`
	// if(quarter>0) return `${quarter}季度`
	if (month > 0) return `${month}月`
	if (dayDiff > 0) return `${dayDiff}天`
}

export function formatFloatingNumber(num, type = 1) {
	if (type === 1) return Math.round(num * 100) / 100
	else {
		const numStr = num.toString()
		const index = numStr.indexOf('.')
		const result = numStr.slice(0, index + 3)
		return Number(result)
	}
}

export function zeroPadding(n) {
	n = n.toString()
	return n[1] ?
		n :
		'0' + n
}

export function getCurrentDate() {
	return getDateFormat(new Date())
}

export function getDateFormat(date = new Date(), showTime = false) {
	const newDate = new Date(date);

	const year = newDate.getFullYear();
	const month = newDate.getMonth() + 1;
	const day = newDate.getDate();

	const hour = newDate.getHours();
	const minute = newDate.getMinutes();
	const second = newDate.getSeconds();

	const t1 = [year, month, day].map(zeroPadding).join('-')
	const t2 = [hour, minute, second].map(zeroPadding).join(':')

	return showTime ? `${t1} ${t2}` : `${t1}`
}

export function getAdjacentDate(type = 'now', num = 1, showTime = false) {
	let date = new Date();

	if (type === 'prev') {
		date.setDate(date.getDate() - num)
	} else if (type === 'next') {
		date.setDate(date.getDate() + num)
	}

	return getDateFormat(date, showTime)
}

export function renderImage(path) {
	const host = Config.host + '/uploadDir'
	// /AreaFolder/20181025/9fed22cda2f64d68a1a8e8c84f1b1506.jpg
	// https://jc.sx2s.net/uploadDir/AreaFolder/20181025/9fed22cda2f64d68a1a8e8c84f1b1506.jpg
	return `${host}${path}`
}

export function getDateTimeDiff(startTime, endTime) {
	const retValue = {};

	const timeDiff = endTime.getTime() - startTime.getTime(); //时间差的毫秒数

	//计算出相差天数
	const days = Math.floor(timeDiff / (24 * 3600 * 1000));
	retValue.Days = days;

	const years = Math.floor(days / 365);
	retValue.Years = years;

	const months = Math.floor(days / 30);
	retValue.Months = months;

	//计算出小时数
	const leave1 = timeDiff % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
	const hours = Math.floor(leave1 / (3600 * 1000));
	retValue.Hours = hours;

	//计算相差分钟数
	const leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
	const minutes = Math.floor(leave2 / (60 * 1000));
	retValue.Minutes = minutes;

	//计算相差秒数
	const leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
	const seconds = Math.round(leave3 / 1000);
	retValue.Seconds = seconds;

	const strTime = "";
	if (years >= 1) {
		strTime = years + "年前";
	} else if (months >= 1) {
		strTime = months + "个月前";
	} else if (days >= 1) {
		strTime = days + "天前";
	} else if (hours >= 1) {
		strTime = hours + "小时前";
	} else {
		strTime = minutes + "分钟前";
	}

	retValue.PubTime = strTime; //帖子,文章,博客发表时间的一种简短表示方法
	return retValue;
}

export function downloadFileAndRename(url, newFileName) {
	// 创建一个 XMLHttpRequest 对象
	const xhr = new XMLHttpRequest();
	xhr.responseType = 'blob';

	xhr.onreadystatechange = function() {
		if (xhr.readyState === 4) {
			if (xhr.status === 200) {
				const blob = xhr.response;
				const a = document.createElement('a');
				a.href = window.URL.createObjectURL(blob);
				a.download = newFileName; // 设置新的文件名
				a.style.display = 'none';
				document.body.appendChild(a);
				a.click();
				document.body.removeChild(a);
			}
		}
	};

	xhr.open('GET', url);
	xhr.send();
}

export function fetchFileAndRename(url, newFileName) {
	fetch(url)
		.then(response => {
			if (!response.ok) {
				throw new Error('Network response was not ok');
			}
			return response.blob();
		})
		.then(blob => {
			const a = document.createElement('a');
			a.href = window.URL.createObjectURL(blob);
			a.download = newFileName; // 设置新的文件名
			a.style.display = 'none';
			document.body.appendChild(a);
			a.click();
			document.body.removeChild(a);
		})
		.catch(error => {
			console.error('Error:', error);
		});
}